package model;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 胡伟
 *	为了提高响应速度, 先在本地文件中读取 项目信息
 */
public class PullFromFile {
	
	/*testcode -- 0
	public static void main(String[] args) {
//		List<Program> programs = pullFromFile.pull("data.txt");
		
		DAO dao = new DAO();
		try {
			List<Program> programs = dao.queryProgram("CS");
			for(Program p:programs)
			{
				System.out.println(p.toString());
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 把本地文本文件数据导入数据库中--0
//		try {
//			dao.fillDataFromSearcher(programs);
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		// 把本地文本文件数据导入数据库中--1
	}
	testcode -- 1*/
	
	
	public static List<Program> pull(String filePath){
		try {
			FileInputStream file_fi = new FileInputStream(filePath);
			InputStreamReader file_sr = new InputStreamReader(file_fi, "UTF-8");
			BufferedReader file = new BufferedReader(file_sr);
			List<Program> programs = new ArrayList<Program>();
			boolean eof = false;
			String line;
			while(!eof) {
				line = file.readLine();
				if(line==null) {
					eof=true;
					break;
				}
				String[] pInfos = line.split("\t");
				Program p = new Program();
				p.setId(pInfos[0]);
				p.setUniversity(pInfos[1]);
				p.setCountry(pInfos[2]);
				p.setProgramName(pInfos[3]);
				p.setSchool(pInfos[4]);
				p.setDegree(pInfos[5]);
				p.setEmail(pInfos[6]);
				p.setPhoneNumber(pInfos[7]);
				p.setLocation(pInfos[8]);
				p.setDeadlineWithAid(pInfos[9]);
				p.setDeadlineWithoutAid(pInfos[10]);
				p.setHomepage(pInfos[11]);
				
				programs.add(p);
			}
			file.close();
			file_sr.close();
			file_fi.close();
			return programs;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.err.println("Error: programs is null!");
		return null;
	}
}
